﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Qreed.Windows.Forms
{
    /// <summary>
    /// Allows a normal menu to be cloned on the fly as a context menu.
    /// </summary>
    public class MenuToContextMenu : ContextMenuStrip
    {
        private ToolStripMenuItem _dummyMenuItem;

        /// <summary>
        /// Initializes a new instance of the <see cref="MenuToContextMenu"/> class.
        /// </summary>
        /// <param name="menuItem">The menu item.</param>
        public MenuToContextMenu(ToolStripMenuItem menuItem)
        {
            _menuItem = menuItem;
            _dummyMenuItem = new ToolStripMenuItem("!DUMMY!");
            Items.Add(_dummyMenuItem);

            menuItem.DropDownOpened += new EventHandler(menuItemDropDownOpened);
        }

        void menuItemDropDownOpened(object sender, EventArgs e)
        {
            if (MenuItem.DropDownItems.Contains(_dummyMenuItem))
            {
                MenuItem.DropDownItems.Remove(_dummyMenuItem);

                while (Items.Count > 0)
                    MenuItem.DropDownItems.Add(Items[0]);

                Items.Add(_dummyMenuItem);
            }
        }

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.ToolStripDropDown.Opening"/> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.ComponentModel.CancelEventArgs"/> that contains the event data.</param>
        protected override void OnOpening(System.ComponentModel.CancelEventArgs e)
        {
            if (Items.Contains(_dummyMenuItem))
            {
                Items.Remove(_dummyMenuItem);

                while (MenuItem.DropDownItems.Count > 0)
                    Items.Add(MenuItem.DropDownItems[0]);

                MenuItem.DropDownItems.Add(_dummyMenuItem);
            }

            base.OnOpening(e);
        }

        private ToolStripMenuItem _menuItem;
        /// <summary>
        /// Gets the menu item.
        /// </summary>
        /// <value>The menu item.</value>
        public ToolStripMenuItem MenuItem
        {
            get { return this._menuItem; }
        }			
    }
}
